package com.witframework.core.schedule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 处理器空闲时通知Observer
 * @author wuxinyang
 */
public class SystemIdelNotify extends Thread {
	public static final int DEFAULT_SAMPLING_INTERVAL = 3000;

	private long m_samplingInterval;

	private static SystemIdelNotify instance;

	private List observer=new ArrayList();

	public static synchronized SystemIdelNotify getCPUMonitor() {
		if (instance == null) {
			instance = new SystemIdelNotify(DEFAULT_SAMPLING_INTERVAL);
		}
		return instance;
	}

	public synchronized long setSamplingInterval(final long samplingInterval) {
		if (samplingInterval <= 0)
			throw new IllegalArgumentException("must be positive: samplingInterval");
		final long old = m_samplingInterval;
		m_samplingInterval = samplingInterval;
		return old;
	}

	protected SystemIdelNotify(final long samplingInterval) {
		setName(getClass().getName() + " [interval: " + samplingInterval + " ms]");
		setDaemon(true);
		setSamplingInterval(samplingInterval);
	}
	public void registerObserver(String name,long interval){
		HashMap map=new HashMap();
		map.put("name",name);
		map.put("interval",new Long(interval));
		map.put("lastTimeMillis",new Long(System.currentTimeMillis()));
		observer.add(map);
	}
	public void registerObserver(String name){
		HashMap map=new HashMap();
		map.put("name",name);
		map.put("interval",new Long(30000));
		map.put("lastTimeMillis",new Long(System.currentTimeMillis()));
		observer.add(map);
	}
	public void run() {
		DataChangeObservableProxy  observableProxy=DataChangeObservableProxy.instance();
		while (!isInterrupted()) {
			final double cpuUsage=SystemInformation.getProcessCPUUsage();
			if(cpuUsage<0.2&&observer.size()>0){
				HashMap map=(HashMap)observer.get(0);
				Object name=map.get("name");
				long interval=((Long)map.get("interval")).longValue();
				long lastTimeMillis=((Long)map.get("lastTimeMillis")).longValue();
				long currentTimeMillis=System.currentTimeMillis();
				if(name!=null&&(currentTimeMillis-lastTimeMillis)>=interval){
					observableProxy.notifyObservers((String)name,null);
					observer.remove(map);
					map.put("lastTimeMillis",new Long(System.currentTimeMillis()));
					observer.add(map);
				}
			}
			final long sleepTime;
			synchronized (this) {
				sleepTime = m_samplingInterval;
			}
			try {
				sleep(sleepTime);
			} catch (InterruptedException e) {
				return;
			}
		}
		synchronized (SystemIdelNotify.class) {
			instance = null;
		}
	}
}

